package admin.auth.domain;

import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import admin.common.domain.req.Oauth2LoginReq;
import admin.common.utils.FieldUtil;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.UUID;

/**
 * @author zgb
 * @date 2024-03-08 14:20
 * @description 设置每次请求都生成新token
 */

public class AuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {

    private static final String CLIENT_ID = FieldUtil.getField(Oauth2LoginReq::getClient_id).getName();

    private static final String SCOPE = "scope";

    private static final String USERNAME = FieldUtil.getField(Oauth2LoginReq::getUsername).getName();

    private static final String CODE = "code";

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap<String, String>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName());
        }
        values.put(CLIENT_ID, authorizationRequest.getClientId());
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<String>(authorizationRequest.getScope())));
        }
        //只要 values 不相同，那么生成的 token 就不相同
        UUID uuid4 = UUID.randomUUID();
        values.put(CODE, uuid4.toString());
        return generateKey(values);
    }
}
